<?php

namespace common\models\datas;

use frontend\models\datas\Admin;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use common\components\helpers\Fun;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\components\extenders\MenuManage;

/**
 * This is the model class for table "{{%card_batch}}".
 *
 * @property integer $id
 * @property string $title
 * @property string $description
 * @property integer $integral
 * @property string $cash
 * @property integer $site_user_id
 * @property integer $site_id
 * @property string $phone
 * @property integer $user_id
 * @property integer $apply_time
 * @property integer $status
 * @property string $info
 * @property integer $grant_time
 * @property string $permission
 * @property integer $number
 * @property integer $batch_start
 * @property integer $batch_end
 * @property integer $city_id
 * @property integer $sendtype
 */
class CardBatch extends \common\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */

    public $city;

    public static function tableName()
    {
        return '{{%card_batch}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'description', 'integral', 'cash', 'phone'], 'required'],
            [['number'], 'required', 'on' => 'apply'],
            ['phone', 'match', 'pattern' => '/^[1][3-8]+\\d{9}/', 'message' => '手机号码格式错误'],
            [['description', 'info', 'permission'], 'string'],
            [['integral', 'site_user_id', 'site_id', 'user_id', 'apply_time', 'status', 'number', 'batch_start', 'batch_end', 'city_id', 'sendtype'], 'integer'],
            [['cash'], 'number'],
            [['title'], 'string', 'max' => 128],
            [['phone'], 'string', 'max' => 20],
            [['number'], 'number_check', 'on' => 'apply'],
            [[ 'batch_start','batch_end'], 'check_number', 'on' => 'verificat'],
            [['description'], 'required', 'when' => function ($model) {
                return $model->status == 2;
            }, 'whenClient' => "function (attribute, value) {
                return $('#cardbatch-status input:checked').val() == '2';
            }"],
//            [['batch_start','batch_end'], 'required', 'when' => function ($model) {
//                return $model->status == 1;
//            }, 'whenClient' => "function (attribute, value) {
//                return $('#cardbatch-status input:checked').val() == '1';
//            }"],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('common', '批次编号'),
            'title' => Yii::t('common', '批次标题'),
            'description' => Yii::t('common', '申请描述'),
            'integral' => Yii::t('common', '包含奖学金'),
            'cash' => Yii::t('common', '包含现金'),
            'site_user_id' => Yii::t('common', '分店申请人'),
            'site_id' => Yii::t('common', '分店编号'),
            'phone' => Yii::t('common', '申请人手机号'),
            'user_id' => Yii::t('common', '总店审核人'),
            'apply_time' => Yii::t('common', '申请时间'),
            'status' => Yii::t('common', '申请状态'),
            'info' => Yii::t('common', '审核意见'),
            'grant_time' => Yii::t('common', '发放时间'),
            'permission' => Yii::t('common', '权限'),
            'number' => Yii::t('common', '本批次数量'),
            'batch_start' => Yii::t('common', '开始编号'),
            'batch_end' => Yii::t('common', '结束编号'),
            'city_id' => Yii::t('common', '城市'),
            'sendtype' => Yii::t('common', '卡类型'),
        ];
    }

    public function extraFields()
    {
        return [
            'admin_name' => function () {
                return ($this->admin != null) ? $this->admin->username : '';
            },
            'site_name' => function () {
                return ($this->site != null) ? $this->site->name : '';
            },
            'backend_admin_name' => function () {
                return ($this->backadmin != null) ? $this->backadmin->username : '';
            },
            'zhtfrontend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'update' => function ($data) {
                            if($data['status']==1){
                                return '<button class="yx-btn-disabled" disabled>修改</button>';
                            }else{
                                return '';
                            }
                        },
                    ]
                )->create();

            },
            'backend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'verificat' => function ($data) {
                            if($data['status']==0){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" disabled>审核</button>';
                            }
                        },
                    ]
                )->create();

            },

        ];
    }


    public function fields()
    {
        $fields = parent::fields();
        $fields['status'] = function () {
            switch ($this->status) {
                case 0:
                    return \Yii::t('frontend', '申请');
                case 1:
                    return \Yii::t('frontend', '通过');
                case 2:
                    return \Yii::t('frontend', '未通过');
            }
        };
        $fields['grant_time'] = function () {
            return \Yii::$app->formatter->asDatetime($this->grant_time);
        };
        $fields['apply_time'] = function () {
            return \Yii::$app->formatter->asDatetime($this->apply_time);
        };
        $fields['sendtype'] = function(){
            switch ($this->sendtype) {
                case 0:
                    return \Yii::t('frontend', '实体卡');
                case 1:
                    return \Yii::t('frontend', '虚拟卡');
                case 2:
                    return \Yii::t('frontend', '推荐卡');
            }
        };
        return $fields;
    }

    public function getAdmin()
    {
        return $this->hasOne(Admin::className(), ['id' => 'site_user_id']);
    }


    public function getSite()
    {
        return $this->hasOne(Site::className(), ['id' => 'site_id']);
    }

    public function getBackadmin()
    {
        return $this->hasOne(\common\models\datas\Admin::className(), ['id' => 'user_id']);
    }

    public function number_check($attribute)
    {
        if ((int)($this->$attribute) > 1) {
            $this->addError($attribute, Yii::t('frontend', '最多申请100张！'));
        }
    }

    public function check_number($attribute){
        if($this->sendtype==0){
            if($this->batch_start==null || $this->batch_end==null ) {
                $this->addError($attribute, Yii::t('frontend', '编号必填!'));
            }
        }
        if($this->batch_start!=null && $this->batch_end!=null ){
            if($this->batch_end<0 ||$this->batch_start<0){
                $this->addError($attribute, Yii::t('frontend', '编号必须为正数!'));
            }
            if($this->batch_end<$this->batch_start){
                $this->addError($attribute, Yii::t('frontend', '结束编号不能小于开始编号!'));
            }
            $count=Card::find()->where(['between','id',$this->batch_start,$this->batch_end])->andWhere(['status'=>1])->count();
            if($count>0){
                $this->addError($attribute, Yii::t('frontend', '起止号码区间不连续!'));
            }
            if(($this->batch_end-$this->batch_start+1)!=$this->number){
                $this->addError($attribute, Yii::t('frontend', '所填起止数值与申请数量不符!'));
            }
        }
    }

    public function check_series($attribute){
        if($this->batch_start!=null){
            if(($this->$attribute-$this->batch_start+1)!=$this->number){
                $this->addError($attribute, Yii::t('frontend', '所填起止数值与申请数量不符!'));
            }
        }
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['apply_time'],
                ],
            ],

        ]);


    }


}
